<template>
  <t-form
    :data="formData"
    :rules="formRules"
    label-width="66px"
    ref="formRef"
    @submit="submitLabel"
  >
    <t-form-item label="选中" name="content">
      <t-input v-model="formData.content" disabled placeholder=""></t-input>
    </t-form-item>
    <t-form-item label="标签" name="tagId">
      <t-select v-model="formData.tagId" placeholder="">
        <t-option
          v-for="tag in tagList"
          :key="tag.id"
          :value="tag.id"
          :label="tag.tagName"
        >
          <t-tag
            variant="light"
            :style="{
              background: preferenceStore.tagColor(tag.id)?.colorValue,
            }"
          >
            {{ tag.tagName }}
          </t-tag>
        </t-option>
        <template #valueDisplay="{ value }">
          <t-tag
            v-if="value"
            variant="light"
            :style="{
              background: preferenceStore.tagColor(value)?.colorValue,
            }"
          >
            {{ tagList.find((t) => t.id === value)?.tagName }}
          </t-tag>
        </template>
      </t-select>
    </t-form-item>
    <t-form-item label="备注" name="remark">
      <t-input v-model="formData.remark" placeholder=""></t-input>
    </t-form-item>
    <t-form-item>
      <t-button block type="submit">提交</t-button>
    </t-form-item>
  </t-form>
</template>

<script setup lang="ts">
import { FormRules, SubmitContext } from 'tdesign-vue-next'
import { reactive, watch, ref } from 'vue'
import { useAnnotationStore } from '@/stores/annotation'
import { storeToRefs } from 'pinia'
import { usePreferenceStore } from '@/stores/preference'

interface FormData {
  content: string
  tagId: string
  remark: string
}

const formData = reactive<FormData>({
  content: '',
  tagId: '',
  remark: '',
})

const formRules: FormRules<FormData> = {
  content: [{ required: true, message: '选中文本不能为空', trigger: 'blur' }],
  tagId: [{ required: true, message: '标签不能为空', trigger: 'blur' }],
}

const annotationStore = useAnnotationStore()
const { tagList, currentLabel } = storeToRefs(annotationStore)

const preferenceStore = usePreferenceStore()

const formRef = ref()
watch(
  () => currentLabel.value.content,
  () => {
    formData.content = currentLabel.value.content
    if (formData.content) {
      formRef.value.clearValidate(['content'])
    }
  }
)

const submitLabel = (context: SubmitContext) => {
  if (context.validateResult === true) {
    currentLabel.value.tagId = formData.tagId
    currentLabel.value.remark = formData.remark
    annotationStore.addLabel().then(() => {
      formData.content = ''
      formData.remark = ''
      if (!preferenceStore.keepTagAfterLabeling) {
        formData.tagId = ''
      }
    })
  }
}
</script>

<style scoped lang="less">
:deep(.t-input.t-is-disabled) {
  background: #fff;
  .t-input__inner {
    color: rgba(0, 0, 0, 0.9);
  }
}
</style>
